package cn.wolfcode.luowowo.comment.service.impl;

import cn.wolfcode.luowowo.comment.domain.TravelComment;
import cn.wolfcode.luowowo.comment.query.TravelCommentQuery;
import cn.wolfcode.luowowo.comment.repository.ITravelCommentRepository;
import cn.wolfcode.luowowo.comment.service.ITravelCommentService;
import com.alibaba.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;

@Service
public class TravelCommentServiceImpl implements ITravelCommentService {
    @Autowired
    private ITravelCommentRepository repository;  //crud

    @Autowired
    private MongoTemplate template;  //高级查询

    @Override
    public TravelComment saveOrUpdate(TravelComment comment) {
        //添加跟更新
        if(!StringUtils.hasLength(comment.getId())){
            comment.setCreateTime(new Date());
        }
        //需要处理引用的评论
        if(comment.getType() == TravelComment.TRAVLE_COMMENT_TYPE){
            if(StringUtils.hasLength(comment.getRefComment().getId())){
                comment.setRefComment(repository.findById(comment.getRefComment().getId()).get());
            }
        }
        repository.save(comment);
        return comment;
    }

    @Override
    public Page query(TravelCommentQuery qo) {

        //需要查询评论列表并分页显示, 而目前现有的api无法直接得到分页对象Page
        //只能通过之前高级查询时候弄PageResult 自己封装Page对象
        Query query = new Query();

        //查询条件
        if(qo.getTravelId() != -1){
            query.addCriteria(Criteria.where("travelId").is(qo.getTravelId()));
        }

        //查总数: select count(*) from xxx where xxxx
        Long total = template.count(query, TravelComment.class);

        if(total == 0){
            return  Page.empty();
        }

        //参数1:当前页, 从0开始  参数2:每页显示条数, 参数3:排序规则  参数4:排序的列
        Pageable pageable = PageRequest.of(qo.getCurrentPage()-1, qo.getPageSize(),
                Sort.Direction.DESC, "createTime");
        query.with(pageable);
        //查当前显示数据:select * from xxx where xxxx limit....
        List<TravelComment> list = template.find(query, TravelComment.class);

        return new PageImpl(list, pageable, total);
    }


    @Override
    public long getCount(Long travelId) {
        Query query = new Query();
        //查询条件
        query.addCriteria(Criteria.where("travelId").is(travelId));
        //查总数: select count(*) from xxx where xxxx
        return template.count(query, TravelComment.class);
    }

}
